package bigoo.peer;

import java.util.Scanner;

import bigoo.peer.ride.Request;
import bigoo.peer.ride.Ride;

public class BigooUI {

    private Scanner input = new Scanner(System.in);
    private BigooPeer bigooPeer;

    public BigooUI(BigooPeer bigooPeer) {
	this.bigooPeer = bigooPeer;
    }

    public void run() {
	boolean exit = false;

	while (!exit) {
	    printAvailableCommands();
	    String command = input.nextLine();
	    exit = processCommand(command);
	}
	System.exit(0);
    }

    private void printAvailableCommands() {
	System.out.println("available commands are:");
	System.out.println(" * publish : publish a ride");
	System.out.println(" * list_rides : list available rides");
	System.out.println(" * request : request a ride");
	System.out.println(" * list_my_requests : list my requests");
	System.out.println(" * list_requests_to_me : list other's requests");
	System.out.println(" * list_confirmed_requests : list confirmed requests");
	System.out.println(" * accept : accept request");
	System.out.println(" * reject : reject request");
	System.out.println(" * leave");
	System.out.print("command: ");
    }

    private boolean processCommand(String command) {
	command = command.trim();
	if (command.equalsIgnoreCase("publish")) {
	    System.out.print("Destination: ");
	    String destination = input.nextLine();
	    System.out.print("Places: ");
	    int places = input.nextInt();
	    input.nextLine();
	    System.out.println("Date (dd-MM-yyyy HH:mm): ");
	    String date = input.nextLine();
	    bigooPeer.publishRide(destination, places, date);
	} else if (command.equalsIgnoreCase("list_rides")) {
	    for (Ride ride : bigooPeer.getAvailableRiders()) {
		System.out.println(ride);
	    }
	} else if (command.equalsIgnoreCase("request")) {
	    System.out.print("Ride ID: ");
	    String rideID = input.nextLine();
	    bigooPeer.requestRide(rideID);
	} else if (command.equalsIgnoreCase("list_my_requests")) {
	    for (Request request : bigooPeer.getMyRequests()) {
		System.out.println(request);
	    }
	} else if (command.equalsIgnoreCase("list_requests_to_me")) {
	    for (Request request : bigooPeer.getOthersRequests()) {
		System.out.println(request);
	    }
	} else if (command.equalsIgnoreCase("list_confirmed_requests")) {
	    for (Request request : bigooPeer.getConfirmedRequests()) {
		System.out.println(request);
	    }
	} else if (command.equalsIgnoreCase("accept")) {
	    System.out.print("Request ID: ");
	    String requestID = input.nextLine();
	    bigooPeer.acceptRequest(requestID);
	} else if (command.equalsIgnoreCase("reject")) {
	    System.out.print("Request ID: ");
	    String requestID = input.nextLine();
	    bigooPeer.rejectRequest(requestID);
	} else if (command.equalsIgnoreCase("leave")) {
	    return true;
	} else {
	    System.err.println("Unknown command!");
	}
	return false;
    }

}
